package com.jsbb.controller.tool;

import com.jsbb.annotation.ApiLog;
import com.jsbb.common.Message;
import com.jsbb.dto.tool.ApiExportDto;
import com.jsbb.dto.tool.ApiQueryDto;
import com.jsbb.pojo.ApiTable;
import com.jsbb.util.SwaggerUtils;
import com.jsbb.util.WordUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 接口文档Controller
 *
 * @author w
 * @date 2021-03-05
 */
@Slf4j
@RestController
@RequestMapping("/tool/api")
@ApiLog("接口文档")
@Api(tags = {"3.1 工具管理-接口文档"})
public class ApiController {

    @PostMapping("/list")
    @ApiOperation(value = "获取列表")
    public Message<List<ApiTable>> list(@RequestBody ApiQueryDto queryDto) {
        if (!StringUtils.hasText(queryDto.getSwaggerUrl())) {
            queryDto.setSwaggerUrl("http://localhost:9900/vue");
        }
        queryDto.setSwaggerUrl(queryDto.getSwaggerUrl().replace("/swagger-ui.html", "").replace("/doc.html", ""));
        List<ApiTable> list = SwaggerUtils.getSwaggerData(queryDto.getSwaggerUrl());
        if (StringUtils.hasText(queryDto.getUrl())) {
            list = list.stream().filter(s -> s.getUrl().contains(queryDto.getUrl())).collect(Collectors.toList());
        }
        if (StringUtils.hasText(queryDto.getTitle())) {
            list = list.stream().filter(s -> (s.getTags() + s.getTitle()).contains(queryDto.getTitle())).collect(Collectors.toList());
        }
        list.sort(Comparator.comparing(ApiTable::getTags));
        return Message.success(list);
    }

    @PostMapping("/export")
    @ApiOperation(value = "导出")
    public void export(@Validated @RequestBody ApiExportDto queryDto, HttpServletResponse response) throws Exception {
        if (!StringUtils.hasText(queryDto.getSwaggerUrl())) {
            queryDto.setSwaggerUrl("http://localhost:9900/vue");
        }
        queryDto.setSwaggerUrl(queryDto.getSwaggerUrl().replace("/swagger-ui.html", "").replace("/doc.html", ""));
        List<ApiTable> list = SwaggerUtils.getSwaggerData(queryDto.getSwaggerUrl());
        list = list.stream().filter(s -> queryDto.getUrlList().contains(s.getUrl())).collect(Collectors.toList());
        Map<String, List<ApiTable>> map = list.stream().collect(Collectors.groupingBy(e -> e.getTags(), TreeMap::new, Collectors.toList()));
        WordUtils.exportSwagger(map, response);
    }
}
